package MyThread;

public class ProAndCon {
    public static void main(String[] args) {
        Res res = new Res();
        Producer producer = new Producer(res);
        Consumer consumer = new Consumer(res);
        producer.start();
        consumer.start();
    }
}

class Res {
    private String name;
    private char sex;

    private boolean flag;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

class Producer extends Thread {
    private Res res;

    public Producer(Res res) {
        this.res = res;
    }

    int count = 0;

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                if (res.isFlag()) {
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (count == 0) {
                    res.setName("严航");
                    res.setSex('男');
                } else {
                    res.setName("Lisa");
                    res.setSex('女');
                }
                res.setFlag(true);
                res.notify();
            }
            count = (count + 1) % 2;

        }
    }
}

class Consumer extends Thread {
    private Res res;

    public Consumer(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                if (!res.isFlag()) {
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println(res.getName() + "," + res.getSex());
                res.setFlag(false);
                res.notify();
            }
        }
    }
}
